import { Message } from "element-ui";
import Vue from "vue";
import VueRouter from "vue-router";
import TheLayout from "../views/TheLayout.vue"

Vue.use(VueRouter)
const routes = [
  // 路由规则 
  {
    path: '/',
    name: 'TheLayout',
    component: TheLayout,
    redirect: '/books',
    children: [
      // 馆藏界面
      {
        path: '/books',
        name: 'BookTable',
        component: () => import("../components/BookTable.vue"),
        meta: {
          auth: false,
          title: '馆藏'
        }
      },
      // 我的借阅 界面
      {
        path: '/borrows',
        name: 'BorrowTable',
        component: () => import("../components/BorrowTable.vue"),
        meta: {
          auth: true,
          title: '借阅'
        },
        beforeEnter: (to, from, next) => {
          // 独享路由
          const stu_info = localStorage.getItem("stu_info")
          const id = JSON.parse(stu_info).id
          if (id) {
            Message({type: 'info', message: '请先登录'})
          }else {
            next()
          }
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'LoginForm',
    component: () => import("../views/LoginForm.vue"),
    meta: {
      auth: false,
      title: '登录'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})
/*  
  全局路由守卫
*/
router.beforeEach((to, from, next) => {
  // 每一次切换路由之前 
  // 判断是否需要 进行登录后才能进入的界面
  if (to.meta.auth) {
    // 馆藏和借阅界面 需要登录后才能访问
    // 学生未登录 跳转登录界面
    if (localStorage.getItem("stu_info")) {
      // 
      next()
    } else {
      Message({type: 'info', message: '请先登录'})
    }
  } else {
    // 不需要 登录直接放行
    next()
  }
})
// 切换之后调用
router.afterEach((to, from) => {
  console.log(to, from)
  document.title = to.meta.title || '主页'
})

export default router;